#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/select.h>
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        printf("Usage:%s <IP> <PORT>\n", argv[0]);
        return -1;
    }

    int fd_s = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd_s)
    {
        perror("socket");
        return -1;
    }
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);

    if (-1 == connect(fd_s, (void *)&saddr, sizeof saddr))
    {
        perror("connect");
        return -1;
    }
    char buf[1024], name[32];
    while (1)
    {

        puts("please input filename");
        memset(buf,0,1024);
        read(STDIN_FILENO, buf, sizeof(buf));
        int len = strlen(buf);
        if (buf[len - 1] == '\n')
        {
            buf[len - 1] = '\0';
        }
        sprintf(name, "%s", buf + 9);
        puts(name);
        int ret = send(fd_s, buf, 1024, 0);
        if (ret == -1)
        {
            perror("send");
            return -1;
        }
        
        puts(name);
        if (0 >= recv(fd_s, buf, 1024, 0))
        {
            break;
        }
        if (0 != strcmp(buf, "OK"))
        {
            puts(" No such file or directory");
            
            break;
        }
        int fd_file = open(name, O_CREAT | O_WRONLY|O_TRUNC, 0664);
        if (-1 == fd_file)
        {
            perror("open");
            break;
        }
        while (1)
        {
            if (0 >= recv(fd_s, &len, 4, 0))
            {
                return -1;
            }
            if (len == 0)
            {
                break;
            }
            printf("%d\n",len);
            while (len > recv(fd_s, buf, len, MSG_PEEK))
                ;
            if (0 >= recv(fd_s, buf, len, 0))
            {
                return -1; 
            }
            write(fd_file, buf, len);
          
        }
        close(fd_file);
          
    }

    return 0;
}
